from industrialai.api.controllers.v1 import controller as v1_controller
from industrialai.api.expose import expose as wsexpose
from industrialai.db import api
from industrialai.db.model import User
from industrialai.pkg.authentication import JWT
import logging
from pecan import abort
from pecan import expose
from pecan import request
from pecan_swagger import decorators as swagger
from wsme import types as wtypes
logger = logging.getLogger(__name__)


class logForm:
    account = wtypes.text
    pwd = wtypes.text


class checkForm:
    id = int
    pwd = wtypes.text


class registryForm:
    account = wtypes.text
    pwd = wtypes.text
    phone = wtypes.text
    mail = wtypes.text
    name = wtypes.text
    number = wtypes.text


@swagger.path("/", "Root")
class RootController(object):

    _custom_actions = {
        'test': ['GET']
    }

    @expose('json')
    def test(self):
        print("123")
        return "test"

    @expose('json')
    def index(self):
        return None

    """
       @api {post} /signin signin
       @apiName SignIn
       @apiGroup User

       @apiBody {String} account    账号
       @apiBody {String} pwd        密码

       @apiSuccess {String} token
       @apiSuccessExample Success-Response:
            {
                "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
            eyJleHAiOjE2NDYzNzc2MjksInVzZXJJZCI6MSwiZ3JvdXBJZCI6MSwicm9sZUlkIjozfQ.
            fEqaaS8c2A_i-2W9D_L76mJac2vcyoS51g6trXr34lM"
            }

        @apiError Unauthorized
        @apiErrorExample {json} Error-Response:
            {
                "faultcode": "Client",
                "faultstring": "This server could not verify that you are
                authorized to access the document you requested. Either
                you supplied the wrong credentials (e.g., bad password),
                or your browser does not understand how to supply the
                credentials required.",
                "debuginfo": null
            }
    """
    @wsexpose(wtypes.text, body=logForm)
    def signin(self, logForm):
        account = logForm.account
        pwd = logForm.pwd
        user = api.get_session().query(User). \
            filter_by(account=account, pwd=pwd).first()
        if user is None:
            abort(401)
        token = JWT.createToken(user.id, user.roleId)
        return {
            "token": token
        }

    """
       @api {post} /pwdcheck check
       @apiName PwdCheck
       @apiGroup User

       @apiBody {Integer} id    用户id
       @apiBody {String} pwd    密码

       @apiSuccess {Bool} result
       @apiSuccessExample Success-Response:
            HTTP/1.1 OK 200
            {
                "result": True          True:校验通过/False:校验失败
            }
    """
    @wsexpose(wtypes.text, body=checkForm)
    def pwdcheck(self, checkForm):
        try:
            api.get_session().query(User). \
                filter_by(id=checkForm.id, pwd=checkForm.pwd).first()
        except Exception:
            return "Failure"
        return "Success"

    """@api {get} /myself get_myself
       @apiName GetMyself
       @apiGroup User

       @apiSuccess (200) {Object} user
       @apiSuccessExample Success-Response:
       {
            "id": 6,                                       用户id
            "number": null,                                身份证号
            "roleId": 3,                                   角色
            "status": 1,                                   状态:0/1
            "create_at": "2022-03-09 11:24:18.856936",     创建时间
            "name": "test",                                名称
            "account": "testsss1-put",                     账号
            "phone": "12345",                              手机号
        }
    """
    @expose('json')
    def myself(self):
        token = request.cookies.get("token")
        message = JWT.deToken(token)
        if message is None:
            abort(401)
        else:
            uId = message.get("userId")
            user = api.get_session().query(User). \
                filter_by(id=uId).first()
            user.pwd = None
            return user

    v1 = v1_controller.v1Controller()
